import { ELOAN_TYPE, ICalculatedResult, ICalculatorParams, IRepaymentSchedule } from './types';
import readline from 'readline';
import { REPORT_RESULT_CN, REPORT_TITLE_CN } from './const';
import fs from 'fs';


const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

/**
 * 输入方法
 */
export const promisifyQuestion = (questionText: string) => {
  return new Promise<string>((resolve) => {
    rl.question(questionText, (responseText) => {
      resolve(responseText);
    });
  });
};


export const renderReportContent = (schedules: IRepaymentSchedule[]) => {
  const rowTitle = REPORT_RESULT_CN.map(([_, title]) => title).join(' ');
  const rowTexts = schedules
    .map((schedule) => {
      const rowData = REPORT_RESULT_CN.map(([dataKey ]) => schedule[dataKey]);
      return rowData.join(' ');
    })
    .join('\n');

  return `${rowTitle}\n${rowTexts}\n`;
};

/**
 * 打印日志
 */
export const toLog = (type: ELOAN_TYPE, result: ICalculatedResult) => {
  const { schedules } = result;
  const calculatorTitle = REPORT_TITLE_CN.get(type);
  const reportContent = renderReportContent(schedules);

  console.log(`${calculatorTitle}还款计划(共${schedules.length}期)\n`);
  console.log(reportContent);
};


export const toCSV = (type: ELOAN_TYPE, result: ICalculatedResult) => {
  const { schedules } = result;
  const calculatorTitle = REPORT_TITLE_CN.get(type);
  const time = new Date().getTime();
  const filename = `dist/${calculatorTitle}还款计划${time}.csv`;
  const reportContent = renderReportContent(schedules);

  // 同步把内容写入文件中
  fs.writeFileSync(filename, reportContent, 'utf-8');
  console.log('报告已经生成：', filename);
};





export const calculateNumToStr = (num: number) => {
  return Math.abs(num).toFixed(2);
};

export const calculateMonthlyInterestRate = (interestRate: number) => {
  return interestRate / 12 / 100;
};

export const calculatePaymentDate = (paymentDateInput: string, month: number) => {
  const paymentDate = new Date(paymentDateInput);
  paymentDate.setMonth(paymentDate.getMonth() + month);
  return paymentDate.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
  });
};

export const calculateWalkMonthly = (
  params: ICalculatorParams,
  calculateMonthly: (month: number) => Omit<IRepaymentSchedule, 'repaymentDate'>,
): ICalculatedResult => {
  const { loanTerm, repaymentDate } = params;

  const results: IRepaymentSchedule[] = [];

  for (let month = 0; month < loanTerm; month++) {
    const currentMonthResult = calculateMonthly(month);
    results.push({ ...currentMonthResult, repaymentDate: calculatePaymentDate(repaymentDate, month) });
  }

  return {
    schedules: results,
  };
};




